package valleyOfDemon;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/**
 * 文件上传
 */
@WebServlet("/ServletDemo07")
@MultipartConfig //Servlet3.0提供的注解,方便获取客户端上传的数据
public class ServletDemo07 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //<input type="file" name="file"> 和name中的一致
        Part part = req.getPart("file");
        //获取文件名
        String fileName = part.getSubmittedFileName();
        //保存在发布路径下，在web根目录下创建写的路径,为了防止路径不被找到，随便加点文件
        String realPath = getServletContext().getRealPath("static/images");
        //File.separator表示路径分隔符，在不同操作系统中路径分隔符不同，用这个都能正常使用
        part.write(realPath + File.separator + fileName);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}







